using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using BaseAmd.BaseDevice;
using BaseAmd.Ret;
using HslCommunication;
using HslCommunicationEx;
using HslCommunicationEx.OpcUa.Client.SieCnc;
using HslCommunicationEx.OpcUa.SieCnc;
using HslCommunicationEx.PeanutNC.Siemens;
using Newtonsoft.Json;
using Catastrophe.Common;
using Catastrophe.Common.AttributeEx;
using Catastrophe.Common.Http;
using RestSharp;
using SiemensAmd.Mmt.Amd;
using SqlSugarEx.Config;
using RestResponse = RestSharp.RestResponse;

namespace SiemensAmd.Mmt.DevQt
{
	public class ToolManagerPi
	{
		private string _serverIp;

		private int _port;

		public const string CreateToolCommand = "/NC/_N_CREATO";

		public const string LoadUnloadCommand = "/NC/_N_TMMVTL";

		public const string DleteCommad = "/NC/_N_DELETO";

		public Dictionary<int, int> _dicMagCapacity = new Dictionary<int, int>
		{
			{ 9998, 4 },
			{ 1, 60 }
		};

		private SiePeanutClient _siePeanutClient;

		private bool _toolSyncIniCompleted = false;

		private Dictionary<int, int> _magCapacityAct;

		private ToolDeviceCacheDal _deviceCacheDal;

		private ToolMagConfigDal _toolMagConfigDal;

		private ToolSyncUtil _toolSyncUtil;

		public string ServerIp
		{
			get
			{
				return this._serverIp;
			}
			set
			{
				this._serverIp = value;
			}
		}

		public int Port
		{
			get
			{
				return this._port;
			}
			set
			{
				this._port = value;
			}
		}

		public int MagCapacity { get; set; }

		public int HttpRequestTimeout { get; set; } = 3000;


		public int NumCuttEdgeParamsTs { get; set; } = 9;


		public int NumCuttEdgeParams { get; set; } = 25;


		public Dictionary<int, int> MagCapacityAct => this._magCapacityAct;

		public string DeviceNo { get; set; }

		public string FmcNo { get; set; } = "SYMG_ZJ_01";


		public ToolDeviceCacheDal DeviceCacheDal => this._deviceCacheDal;

		public ToolMagConfigDal ToolMagConfigDal => this._toolMagConfigDal;

		public int[] CacheToolBuff { get; set; } = new int[1];


		public List<ToolDeviceCacheUnionEntity> ToolCacheList { get; set; } = new List<ToolDeviceCacheUnionEntity>();


		public ToolManagerPi(string serverIp, int port)
		{
			this._serverIp = serverIp;
			this._port = port;
			this._siePeanutClient = new SiePeanutClient(this._serverIp, this._port);
			this._toolSyncUtil = new ToolSyncUtil();
		}

		public void SetMagCapacity(int mag, int capacity)
		{
			if (this._dicMagCapacity.ContainsKey(mag))
			{
				this._dicMagCapacity[mag] = capacity;
			}
			else
			{
				this._dicMagCapacity.Add(mag, capacity);
			}
		}

		public GOperateAmdRet<OpcUaToolBaseEntity> QuerySingle(int tNo, string channel = "1")
		{
			GOperateAmdRet<OpcUaToolBaseEntity> gOperateAmdRet = new GOperateAmdRet<OpcUaToolBaseEntity>();
			if (tNo <= 0)
			{
				gOperateAmdRet.Message = "invalid tNo";
				return gOperateAmdRet;
			}
			List<string> list = new List<string>();
			OpcUaToolBaseEntity opcUaToolBaseEntity = new OpcUaToolBaseEntity();
			var list2 = (from x in typeof(OpcUaToolBaseEntity).GetProperties()
				select new
				{
					Property = x,
					ComOpcUaAb = (Attribute.GetCustomAttribute(x, typeof(ComOpcUaDataAttribute)) as ComOpcUaDataAttribute)
				}).Where(x =>
			{
				ComOpcUaDataAttribute comOpcUaAb = x.ComOpcUaAb;
				return comOpcUaAb != null && !comOpcUaAb.Ignore;
			}).ToList();
			foreach (var item2 in list2)
			{
				string item = item2.ComOpcUaAb.Adr.Replace("{toolAreaNo}", channel).Replace("{tNo}", ToolManagerPi.GetDNo(tNo));
				list.Add(item);
			}
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			dictionary.Add("Custom-Param1", JsonConvert.SerializeObject(list));
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(58, 2);
			defaultInterpolatedStringHandler.AppendLiteral("http://");
			defaultInterpolatedStringHandler.AppendFormatted(this._serverIp);
			defaultInterpolatedStringHandler.AppendLiteral(":");
			defaultInterpolatedStringHandler.AppendFormatted(this._port);
			defaultInterpolatedStringHandler.AppendLiteral("/CapService/CapSyncReadMulti?pipeNo=0&timeout=3000");
			RestResponse restResponse = HttpUtil.RequestBehaviorSync(defaultInterpolatedStringHandler.ToStringAndClear(), Method.Get, "", isToken: true, isJson: true, keepAlive: true, dictionary, this.HttpRequestTimeout);
			if (!restResponse.IsSuccessful)
			{
				gOperateAmdRet.Message = restResponse.ErrorMessage;
				return gOperateAmdRet;
			}
			GOperateAmdRet<Dictionary<string, string>> gOperateAmdRet2 = JsonConvert.DeserializeObject<GOperateAmdRet<Dictionary<string, string>>>(restResponse.Content);
			if (!gOperateAmdRet2.Success)
			{
				gOperateAmdRet.Message = gOperateAmdRet2.Message;
				return gOperateAmdRet;
			}
			List<string> list3 = gOperateAmdRet2.Content.Values.ToList();
			foreach (var item3 in list2)
			{
				string key = item3.ComOpcUaAb.Adr.Replace("{toolAreaNo}", channel).Replace("{tNo}", ToolManagerPi.GetDNo(tNo));
				if (gOperateAmdRet2.Content.ContainsKey(key))
				{
					item3.Property.SetValue(opcUaToolBaseEntity, Convert.ChangeType(gOperateAmdRet2.Content[key], item3.Property.PropertyType));
					opcUaToolBaseEntity.ToolNo = tNo;
				}
			}
			gOperateAmdRet.Content = opcUaToolBaseEntity;
			gOperateAmdRet.Success = true;
			return gOperateAmdRet;
		}

		public GOperateAmdRet<List<ToolEntitySimple>> QuerySimple()
		{
			List<string> value = new List<string> { "ToolIdent", "ToolInPlace", "ToolInMag", "DuploNo" };
			GOperateAmdRet<List<ToolEntitySimple>> gOperateAmdRet = new GOperateAmdRet<List<ToolEntitySimple>>();
			List<ToolEntitySimple> list = new List<ToolEntitySimple>();
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			Dictionary<string, List<string>> dictionary2 = new Dictionary<string, List<string>>();
			dictionary2.Add("name", value);
			string value2 = JsonConvert.SerializeObject(dictionary2);
			dictionary.Add("Custom-Param1", value2);
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(35, 2);
			defaultInterpolatedStringHandler.AppendLiteral("http://");
			defaultInterpolatedStringHandler.AppendFormatted(this._serverIp);
			defaultInterpolatedStringHandler.AppendLiteral(":");
			defaultInterpolatedStringHandler.AppendFormatted(this._port);
			defaultInterpolatedStringHandler.AppendLiteral("/CapService/ReadToolDetails");
			RestResponse restResponse = HttpUtil.RequestBehaviorSync(defaultInterpolatedStringHandler.ToStringAndClear(), Method.Get, "", isToken: true, isJson: true, keepAlive: true, dictionary, this.HttpRequestTimeout);
			if (!restResponse.IsSuccessful)
			{
				gOperateAmdRet.Message = restResponse.ErrorMessage;
				return gOperateAmdRet;
			}
			GOperateAmdRet<List<OpcUaToolBaseEntity>> gOperateAmdRet2 = JsonConvert.DeserializeObject<GOperateAmdRet<List<OpcUaToolBaseEntity>>>(restResponse.Content);
			if (!gOperateAmdRet2.Success)
			{
				gOperateAmdRet.Message = gOperateAmdRet2.Message;
				return gOperateAmdRet;
			}
			IEnumerable<IGrouping<int, OpcUaToolBaseEntity>> enumerable = from x in gOperateAmdRet2.Content
				group x by x.ToolInMag;
			foreach (IGrouping<int, OpcUaToolBaseEntity> item in enumerable)
			{
				int key = item.Key;
				int num = 0;
				if (this._dicMagCapacity.ContainsKey(item.Key))
				{
					num = this._dicMagCapacity[item.Key];
				}
				List<ToolEntitySimple> list2 = new List<ToolEntitySimple>();
				if (num > item.Count())
				{
					List<int> list3 = (from x in item
						where x.ToolInPlace > 0
						select x.ToolInPlace).ToList();
					int i;
					for (i = 1; i <= num; i++)
					{
						if (list3.Contains(i))
						{
							OpcUaToolBaseEntity opcUaToolBaseEntity = item.First((OpcUaToolBaseEntity x) => x.ToolInPlace == i);
							if (opcUaToolBaseEntity != null)
							{
								list2.Add(new ToolEntitySimple
								{
									ToolNo = opcUaToolBaseEntity.ToolNo,
									ToolIdent = opcUaToolBaseEntity.ToolIdent,
									DuploNo = opcUaToolBaseEntity.DuploNo,
									ToolInPlace = opcUaToolBaseEntity.ToolInPlace,
									ToolInMag = key,
									IsEmpty = false
								});
							}
						}
						else
						{
							list2.Add(new ToolEntitySimple
							{
								ToolInPlace = i,
								IsEmpty = true,
								ToolInMag = key
							});
						}
					}
				}
				else
				{
					list2 = item.Select((OpcUaToolBaseEntity x) => new ToolEntitySimple
					{
						ToolNo = x.ToolNo,
						ToolIdent = x.ToolIdent,
						DuploNo = x.DuploNo,
						ToolInPlace = x.ToolInPlace,
						IsEmpty = false,
						ToolInMag = x.ToolInMag
					}).ToList();
				}
				list.AddRange(list2.OrderBy((ToolEntitySimple x) => x.ToolInPlace).ToList());
			}
			gOperateAmdRet.Content = list;
			gOperateAmdRet.Success = true;
			return gOperateAmdRet;
		}
		/// <summary>
		/// 请求所有刀具
		/// </summary>
		/// <param name="channelNo"></param>
		/// <param name="acceptNotify"></param>
		/// <returns></returns>
		public GOperateRet<List<OpcUaToolBaseEntity>> QueryToolAll(int channelNo = 1, bool acceptNotify = true)
		{
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(57, 4);
			defaultInterpolatedStringHandler.AppendLiteral("http://");
			defaultInterpolatedStringHandler.AppendFormatted(this.ServerIp);
			defaultInterpolatedStringHandler.AppendLiteral(":");
			defaultInterpolatedStringHandler.AppendFormatted(this.Port);
			defaultInterpolatedStringHandler.AppendLiteral("/CapService/QueryToolAll?channelNo=");
			defaultInterpolatedStringHandler.AppendFormatted(channelNo);
			defaultInterpolatedStringHandler.AppendLiteral("&acceptNotify=");
			defaultInterpolatedStringHandler.AppendFormatted(acceptNotify);
			string url = defaultInterpolatedStringHandler.ToStringAndClear();
			GOperateRet<List<OpcUaToolBaseEntity>> gOperateRet = new GOperateRet<List<OpcUaToolBaseEntity>>();
			RestResponse restResponse = HttpUtil.RequestBehaviorSync(url, Method.Get, "");
			if (!restResponse.IsSuccessful)
			{
				gOperateRet.Message = restResponse.ErrorMessage;
				return gOperateRet;
			}
			List<OpcUaToolBaseEntity> list = new List<OpcUaToolBaseEntity>();
			GOperateAmdRet<List<OpcUaToolBaseEntity>> gOperateAmdRet = JsonConvert.DeserializeObject<GOperateAmdRet<List<OpcUaToolBaseEntity>>>(restResponse.Content);
			gOperateRet.Success = gOperateAmdRet.Success;
			gOperateRet.Message = gOperateAmdRet.Message;
			gOperateRet.Content = gOperateAmdRet.Content;
			return gOperateRet;
		}


		public static string GetDNo(int toolNo, int digital = 5)
		{
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(1, 1);
			defaultInterpolatedStringHandler.AppendLiteral("D");
			defaultInterpolatedStringHandler.AppendFormatted(digital);
			return toolNo.ToString(defaultInterpolatedStringHandler.ToStringAndClear());
		}


		public GOperateAmdRet<List<ToolPalceDataEntity>> QueryPlaceData(int magNo, int startLoc, int endLoc, int numMagPlaceParams = 11)
		{
			GOperateAmdRet<List<ToolPalceDataEntity>> gOperateAmdRet = new GOperateAmdRet<List<ToolPalceDataEntity>>();
			PropertyInfo[] properties = typeof(ToolPalceDataEntity).GetProperties();
			List<string> list = new List<string>();
			Dictionary<ToolPalceDataEntity, Dictionary<string, PropertyInfo>> dictionary = new Dictionary<ToolPalceDataEntity, Dictionary<string, PropertyInfo>>();
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler;
			for (int i = startLoc; i <= endLoc; i++)
			{
				ToolPalceDataEntity key = new ToolPalceDataEntity
				{
					ToolInPlace = i
				};
				Dictionary<string, PropertyInfo> dictionary2 = new Dictionary<string, PropertyInfo>();
				for (int j = 1; j <= 5; j++)
				{
					int value = (i - 1) * numMagPlaceParams + j;
					defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(28, 2);
					defaultInterpolatedStringHandler.AppendLiteral("/Tool/Magazine/placeData[u");
					defaultInterpolatedStringHandler.AppendFormatted(magNo);
					defaultInterpolatedStringHandler.AppendLiteral(",");
					defaultInterpolatedStringHandler.AppendFormatted(value);
					defaultInterpolatedStringHandler.AppendLiteral("]");
					string text = defaultInterpolatedStringHandler.ToStringAndClear();
					switch (j)
					{
					case 1:
						dictionary2.Add(text, properties.First((PropertyInfo x) => x.Name == "PlaceType1"));
						list.Add(text);
						break;
					case 3:
						dictionary2.Add(text, properties.First((PropertyInfo x) => x.Name == "TNo"));
						list.Add(text);
						break;
					case 5:
						dictionary2.Add(text, properties.First((PropertyInfo x) => x.Name == "PlaceState"));
						list.Add(text);
						break;
					}
				}
				dictionary.Add(key, dictionary2);
			}
			StringBuilder stringBuilder = new StringBuilder("[");
			foreach (string item in list)
			{
				StringBuilder stringBuilder2 = stringBuilder;
				StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(3, 1, stringBuilder2);
				handler.AppendLiteral("\"");
				handler.AppendFormatted(item);
				handler.AppendLiteral("\",");
				stringBuilder2.Append(ref handler);
			}
			string value2 = stringBuilder.Remove(stringBuilder.Length - 1, 1).Append("]").ToString();
			Dictionary<string, string> dictionary3 = new Dictionary<string, string>();
			dictionary3.Add("Custom-Param1", value2);
			defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(49, 2);
			defaultInterpolatedStringHandler.AppendLiteral("http://");
			defaultInterpolatedStringHandler.AppendFormatted(this._serverIp);
			defaultInterpolatedStringHandler.AppendLiteral(":");
			defaultInterpolatedStringHandler.AppendFormatted(this._port);
			defaultInterpolatedStringHandler.AppendLiteral("/CapService/CapSyncReadMulti?timeout=3000");
			RestResponse restResponse = HttpUtil.RequestBehaviorSync(defaultInterpolatedStringHandler.ToStringAndClear(), Method.Get, "", isToken: true, isJson: true, keepAlive: true, dictionary3, this.HttpRequestTimeout);
			if (!restResponse.IsSuccessful)
			{
				gOperateAmdRet.Message = restResponse.ErrorMessage;
				return gOperateAmdRet;
			}
			GOperateAmdRet<Dictionary<string, string>> gOperateAmdRet2 = JsonConvert.DeserializeObject<GOperateAmdRet<Dictionary<string, string>>>(restResponse.Content);
			List<ToolPalceDataEntity> list2 = new List<ToolPalceDataEntity>();
			if (!gOperateAmdRet2.Success)
			{
				gOperateAmdRet.Message = gOperateAmdRet2.Message;
				return gOperateAmdRet;
			}
			foreach (ToolPalceDataEntity key2 in dictionary.Keys)
			{
				Dictionary<string, PropertyInfo> dictionary4 = dictionary[key2];
				foreach (string key3 in dictionary4.Keys)
				{
					if (gOperateAmdRet2.Content.ContainsKey(key3))
					{
						dictionary4[key3].SetValue(key2, Convert.ChangeType(gOperateAmdRet2.Content[key3], dictionary4[key3].PropertyType));
					}
				}
				list2.Add(key2);
			}
			gOperateAmdRet.Success = true;
			gOperateAmdRet.Content = list2;
			return gOperateAmdRet;
		}

		public OperateAmdRet EditTool(OpcUaToolBaseEntity entity, int dNo, bool isUpdateMagType = false, int sendTimeout = 3000)
		{
			if (entity == null)
			{
				throw new ArgumentNullException("entity");
			}
			OperateAmdRet operateAmdRet = new OperateAmdRet();
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler;
			if (dNo < 1)
			{
				OperateAmdRet operateAmdRet2 = operateAmdRet;
				defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(12, 1);
				defaultInterpolatedStringHandler.AppendLiteral("invalid dNo ");
				defaultInterpolatedStringHandler.AppendFormatted(dNo);
				operateAmdRet2.Message = defaultInterpolatedStringHandler.ToStringAndClear();
				return operateAmdRet;
			}
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			string value = "";
			string value2 = "";
			var list = (from x in typeof(OpcUaToolBaseEntity).GetProperties()
				select new
				{
					Property = x,
					ComOpcUaAb = (Attribute.GetCustomAttribute(x, typeof(ComOpcUaDataAttribute)) as ComOpcUaDataAttribute),
					MultiToolDataAb = (Attribute.GetCustomAttribute(x, typeof(MultiToolDataAttribute)) as MultiToolDataAttribute)
				}).Where(x =>
			{
				ComOpcUaDataAttribute comOpcUaAb = x.ComOpcUaAb;
				return comOpcUaAb != null && !comOpcUaAb.Ignore;
			}).ToList();
			foreach (var item in list)
			{
				if ((!isUpdateMagType || !(item.Property.Name == "ToolPlaceSpec")) && item.ComOpcUaAb.AllowOpr != AllowOprEnum.ReadAndWrite)
				{
					continue;
				}
				string text = item.ComOpcUaAb.Adr;
				string text2 = text.Split(',').Last((string x) => x.Trim() != "");
				if (int.TryParse(text2.Replace("]", ""), out var result) && item.MultiToolDataAb != null)
				{
					if (item.MultiToolDataAb.ToolModule == ToolModuleEnum.Supervision)
					{
						text = text.Replace(text2, "") + ((dNo - 1) * this.NumCuttEdgeParamsTs + result) + "]";
					}
					else
					{
						if (item.MultiToolDataAb.ToolModule != ToolModuleEnum.EdgeData)
						{
							continue;
						}
						text = text.Replace(text2, "") + ((dNo - 1) * this.NumCuttEdgeParams + result) + "]";
					}
				}
				string text3 = text.Replace("{toolAreaNo}", "1").Replace("{tNo}", ToolManagerPi.GetDNo(entity.ToolNo));
				object value3 = item.Property.GetValue(entity, null);
				dictionary.Add(text3, value3?.ToString() ?? "");
				if (item.Property.Name == "ToolState")
				{
					value = text3;
					value2 = value3?.ToString() ?? "";
				}
			}
			Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
			string value4 = JsonConvert.SerializeObject(dictionary);
			dictionary2.Add("Custom-Param1", value4);
			defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(46, 3);
			defaultInterpolatedStringHandler.AppendLiteral("http://");
			defaultInterpolatedStringHandler.AppendFormatted(this._serverIp);
			defaultInterpolatedStringHandler.AppendLiteral(":");
			defaultInterpolatedStringHandler.AppendFormatted(this._port);
			defaultInterpolatedStringHandler.AppendLiteral("/CapService/CapSyncWriteMulti?timeout=");
			defaultInterpolatedStringHandler.AppendFormatted(sendTimeout);
			RestResponse restResponse = HttpUtil.RequestBehaviorSync(defaultInterpolatedStringHandler.ToStringAndClear(), Method.Get, "", isToken: true, isJson: true, keepAlive: true, dictionary2, this.HttpRequestTimeout);
			if (!restResponse.IsSuccessful)
			{
				operateAmdRet.Message = restResponse.ErrorMessage;
				return operateAmdRet;
			}
			operateAmdRet = JsonConvert.DeserializeObject<OperateAmdRet>(restResponse.Content);
			if (operateAmdRet.Success)
			{
				defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(59, 5);
				defaultInterpolatedStringHandler.AppendLiteral("http://");
				defaultInterpolatedStringHandler.AppendFormatted(this._serverIp);
				defaultInterpolatedStringHandler.AppendLiteral(":");
				defaultInterpolatedStringHandler.AppendFormatted(this._port);
				defaultInterpolatedStringHandler.AppendLiteral("/CapService/CapSyncWriteSingle?adr=");
				defaultInterpolatedStringHandler.AppendFormatted(value);
				defaultInterpolatedStringHandler.AppendLiteral("&value=");
				defaultInterpolatedStringHandler.AppendFormatted(value2);
				defaultInterpolatedStringHandler.AppendLiteral("&timeout=");
				defaultInterpolatedStringHandler.AppendFormatted(sendTimeout);
				RestResponse restResponse2 = HttpUtil.RequestBehaviorSync(defaultInterpolatedStringHandler.ToStringAndClear(), Method.Get, "", isToken: true, isJson: true, keepAlive: true, null, this.HttpRequestTimeout);
				if (!restResponse2.IsSuccessful)
				{
					operateAmdRet.Success = false;
					operateAmdRet.Message = restResponse2.ErrorMessage;
					return operateAmdRet;
				}
				OperateAmdRet operateAmdRet3 = JsonConvert.DeserializeObject<OperateAmdRet>(restResponse2.Content);
				if (!operateAmdRet.Success)
				{
					operateAmdRet.Success = false;
					operateAmdRet.Message = "update toolState failed " + restResponse2.ErrorMessage;
					return operateAmdRet;
				}
			}
			operateAmdRet.Success = true;
			return operateAmdRet;
		}
		
		/// <summary>
		/// 编辑刀具
		/// </summary>
		/// <param name="entity"></param>
		/// <param name="isUpdateMagType"></param>
		/// <param name="sendTimeout"></param>
		/// <returns></returns>
		/// <exception cref="ArgumentNullException"></exception>
		public OperateAmdRet EditTool(OpcUaToolBaseEntity entity, bool isUpdateMagType = false, int sendTimeout = 3000)
		{
			if (entity == null)
			{
				throw new ArgumentNullException("entity");
			}
			OperateAmdRet operateAmdRet = new OperateAmdRet();
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			string value = "";
			string value2 = "";
			var list = (from x in typeof(OpcUaToolBaseEntity).GetProperties()
				select new
				{
					Property = x,
					ComOpcUaAb = (Attribute.GetCustomAttribute(x, typeof(ComOpcUaDataAttribute)) as ComOpcUaDataAttribute)
				}).Where(x =>
			{
				ComOpcUaDataAttribute comOpcUaAb = x.ComOpcUaAb;
				return comOpcUaAb != null && !comOpcUaAb.Ignore;
			}).ToList();
			foreach (var item in list)
			{
				if ((isUpdateMagType && item.Property.Name == "ToolPlaceSpec") || item.ComOpcUaAb.AllowOpr == AllowOprEnum.ReadAndWrite)
				{
					string text = item.ComOpcUaAb.Adr.Replace("{toolAreaNo}", "1").Replace("{tNo}", ToolManagerPi.GetDNo(entity.ToolNo));
					object value3 = item.Property.GetValue(entity, null);
					dictionary.Add(text, value3?.ToString() ?? "");
					if (item.Property.Name == "ToolState")
					{
						value = text;
						value2 = value3?.ToString() ?? "";
					}
				}
			}
			Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
			string value4 = JsonConvert.SerializeObject(dictionary);
			dictionary2.Add("Custom-Param1", value4);
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(46, 3);
			defaultInterpolatedStringHandler.AppendLiteral("http://");
			defaultInterpolatedStringHandler.AppendFormatted(this._serverIp);
			defaultInterpolatedStringHandler.AppendLiteral(":");
			defaultInterpolatedStringHandler.AppendFormatted(this._port);
			defaultInterpolatedStringHandler.AppendLiteral("/CapService/CapSyncWriteMulti?timeout=");
			defaultInterpolatedStringHandler.AppendFormatted(sendTimeout);
			RestResponse restResponse = HttpUtil.RequestBehaviorSync(defaultInterpolatedStringHandler.ToStringAndClear(), Method.Get, "", isToken: true, isJson: true, keepAlive: true, dictionary2, this.HttpRequestTimeout);
			if (!restResponse.IsSuccessful)
			{
				operateAmdRet.Message = "更新刀具信息" + restResponse.ErrorMessage;
				return operateAmdRet;
			}
			operateAmdRet = JsonConvert.DeserializeObject<OperateAmdRet>(restResponse.Content);
			if (operateAmdRet.Success)
			{
				defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(59, 5);
				defaultInterpolatedStringHandler.AppendLiteral("http://");
				defaultInterpolatedStringHandler.AppendFormatted(this._serverIp);
				defaultInterpolatedStringHandler.AppendLiteral(":");
				defaultInterpolatedStringHandler.AppendFormatted(this._port);
				defaultInterpolatedStringHandler.AppendLiteral("/CapService/CapSyncWriteSingle?adr=");
				defaultInterpolatedStringHandler.AppendFormatted(value);
				defaultInterpolatedStringHandler.AppendLiteral("&value=");
				defaultInterpolatedStringHandler.AppendFormatted(value2);
				defaultInterpolatedStringHandler.AppendLiteral("&timeout=");
				defaultInterpolatedStringHandler.AppendFormatted(sendTimeout);
				RestResponse restResponse2 = HttpUtil.RequestBehaviorSync(defaultInterpolatedStringHandler.ToStringAndClear(), Method.Get, "", isToken: true, isJson: true, keepAlive: true, null, this.HttpRequestTimeout);
				if (!restResponse2.IsSuccessful)
				{
					operateAmdRet.Success = false;
					operateAmdRet.Message = "更新刀具状态" + restResponse2.ErrorMessage;
					return operateAmdRet;
				}
				OperateAmdRet operateAmdRet2 = JsonConvert.DeserializeObject<OperateAmdRet>(restResponse2.Content);
				if (!operateAmdRet.Success)
				{
					operateAmdRet.Success = false;
					operateAmdRet.Message = "update toolState failed " + restResponse2.ErrorMessage;
					return operateAmdRet;
				}
			}
			operateAmdRet.Success = true;
			return operateAmdRet;
		}

		public OperateAmdRet CreateTool(int tNo, string channel = "401")
		{
			string text = tNo.ToString("D5");
			return this.ExcutePi("/NC/_N_CREATO", channel, text);
		}

		public OperateAmdRet LoadTool(int tNo, int dstLoc, string channel = "401", string srcLoc = "00001", string srcMag = "09999", string dstMag = "00001")
		{
			OperateAmdRet operateAmdRet = this.ExcutePi("/NC/_N_TMMVTL", channel, ToolManagerPi.GetDNo(tNo), srcLoc, srcMag, dstLoc.ToString("D5"), dstMag);
			if (!operateAmdRet.Success)
			{
				return operateAmdRet;
			}
			GOperateAmdRet<OpcUaToolBaseEntity> gOperateAmdRet = this.QuerySingle(tNo);
			if (gOperateAmdRet.Success && gOperateAmdRet.Content.ToolInPlace == dstLoc)
			{
				operateAmdRet.Success = true;
				return operateAmdRet;
			}
			operateAmdRet.Success = false;
			operateAmdRet.Message = "load faild!(check)";
			this.DeleteTool(tNo);
			return operateAmdRet;
		}

		public OperateAmdRet UnloadTool(int tNo, string channel = "401", string dstLoc = "00001", string dstMag = "09999")
		{
			string text = tNo.ToString("D5");
			return this.ExcutePi("/NC/_N_TMMVTL", channel, text, "-0001", "-0001", dstLoc, dstMag);
		}

		public OperateAmdRet DeleteTool(int tNo, string channel = "401")
		{
			string text = tNo.ToString("D5");
			return this.ExcutePi("/NC/_N_DELETO", channel, text);
		}

		public OperateAmdRet CreateLoad(OpcUaToolBaseEntity entity, int LoadPlace, int toolState = 131)
		{
			OperateAmdRet operateAmdRet = new OperateAmdRet();
			OperateAmdRet operateAmdRet2 = this.CreateTool(entity.ToolNo);
			if (!operateAmdRet2.Success)
			{
				OperateAmdRet operateAmdRet3 = this.DeleteTool(entity.ToolNo);
				operateAmdRet.Message = operateAmdRet2.Message;
				return operateAmdRet;
			}
			Thread.Sleep(200);
			if (entity.ToolState <= 0)
			{
				entity.ToolState = toolState;
			}
			OperateAmdRet operateAmdRet4 = this.EditTool(entity, isUpdateMagType: true);
			if (!operateAmdRet4.Success)
			{
				OperateAmdRet operateAmdRet5 = this.DeleteTool(entity.ToolNo);
				operateAmdRet.Message = operateAmdRet4.Message;
				return operateAmdRet;
			}
			Thread.Sleep(500);
			OperateAmdRet operateAmdRet6 = this.LoadTool(entity.ToolNo, LoadPlace);
			if (!operateAmdRet6.Success)
			{
				OperateAmdRet operateAmdRet7 = this.DeleteTool(entity.ToolNo);
				operateAmdRet.Message = operateAmdRet6.Message;
				return operateAmdRet;
			}
			Thread.Sleep(500);
			GOperateAmdRet<OpcUaToolBaseEntity> gOperateAmdRet = this.QuerySingle(entity.ToolNo);
			if (gOperateAmdRet.Success && gOperateAmdRet.Content.ToolInPlace == LoadPlace)
			{
				operateAmdRet.Success = true;
				return operateAmdRet;
			}
			operateAmdRet.Message = "load faild!(check)";
			this.DeleteTool(entity.ToolNo);
			return operateAmdRet;
		}

		public OperateAmdRet CreateEdit(OpcUaToolBaseEntity entity, int toolState = 131)
		{
			OperateAmdRet operateAmdRet = new OperateAmdRet();
			OperateAmdRet operateAmdRet2 = this.CreateTool(entity.ToolNo);
			if (!operateAmdRet2.Success)
			{
				OperateAmdRet operateAmdRet3 = this.DeleteTool(entity.ToolNo);
				operateAmdRet.Message = operateAmdRet2.Message;
				return operateAmdRet;
			}
			Thread.Sleep(200);
			if (entity.ToolState <= 0)
			{
				entity.ToolState = toolState;
			}
			OperateAmdRet operateAmdRet4 = this.EditTool(entity, isUpdateMagType: true);
			if (!operateAmdRet4.Success)
			{
				OperateAmdRet operateAmdRet5 = this.DeleteTool(entity.ToolNo);
				operateAmdRet.Message = operateAmdRet4.Message;
				return operateAmdRet;
			}
			operateAmdRet.Success = true;
			return operateAmdRet;
		}

		public OperateAmdRet UnloadDelete(int toolNo, bool isDelete = true)
		{
			OperateAmdRet operateAmdRet = new OperateAmdRet();
			OperateAmdRet operateAmdRet2 = this.UnloadTool(toolNo);
			if (!operateAmdRet2.Success)
			{
				operateAmdRet.Message = "卸载失败" + operateAmdRet2.Message;
				return operateAmdRet;
			}
			Thread.Sleep(500);
			if (isDelete)
			{
				OperateAmdRet operateAmdRet3 = this.DeleteTool(toolNo);
				if (!operateAmdRet3.Success)
				{
					operateAmdRet.Message = "删除失败" + operateAmdRet3.Message;
					return operateAmdRet;
				}
			}
			GOperateAmdRet<List<ToolEntitySimple>> gOperateAmdRet = this.QuerySimple();
			if (isDelete)
			{
				if (gOperateAmdRet.Success && gOperateAmdRet.Content.All((ToolEntitySimple x) => x.ToolNo != toolNo))
				{
					operateAmdRet.Success = true;
					return operateAmdRet;
				}
				operateAmdRet.Message = "unload faild!(check)";
				return operateAmdRet;
			}
			ToolEntitySimple toolEntitySimple = gOperateAmdRet.Content.FirstOrDefault((ToolEntitySimple x) => x.ToolNo == toolNo);
			if (toolEntitySimple != null && toolEntitySimple.ToolInMag == 0)
			{
				operateAmdRet.Success = true;
				return operateAmdRet;
			}
			operateAmdRet.Message = "unload faild!(check)";
			return operateAmdRet;
		}

		public GOperateAmdRet<Tuple<int, int>> QueryEmptyPlace(int channelNo = 401, int startMag = 1, int? startToolPlace = null, int endMag = 1, int? endToolPlace = null, int referMag = 0, int referToolPlace = 0, int leftOffset = 1, int rightOffset = 1, int topOffset = 1, int bottomOffset = 1, int toolPlaceType = 1, int queryDirect = 0)
		{
			GOperateAmdRet<Tuple<int, int>> gOperateAmdRet = new GOperateAmdRet<Tuple<int, int>>();
			string text = ((!startToolPlace.HasValue) ? "-0001" : startToolPlace.Value.ToString("D5"));
			string text2 = ((!endToolPlace.HasValue) ? "-0001" : endToolPlace.Value.ToString("D5"));
			OperateAmdRet operateAmdRet = this.ExcutePi("_N_TMFPBP", channelNo.ToString(), startMag.ToString("D5"), text, endMag.ToString("D5"), text2, referMag.ToString("D5"), referToolPlace.ToString("D5"), leftOffset.ToString("D5"), rightOffset.ToString("D5"), topOffset.ToString("D5"), bottomOffset.ToString("D5"), toolPlaceType.ToString("D5"), queryDirect.ToString("D5"));
			if (!operateAmdRet.Success)
			{
				gOperateAmdRet.Message = operateAmdRet.Message;
				return gOperateAmdRet;
			}
			Thread.Sleep(200);
			string text3 = "/Tool/MagazineConfiguration/magCMCmdPar1";
			string text4 = "/Tool/MagazineConfiguration/magCMCmdPar2";
			int result = -1;
			int result2 = -1;
			List<string> value = new List<string> { text3, text4 };
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			dictionary.Add("Custom-Param1", JsonConvert.SerializeObject(value));
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(58, 2);
			defaultInterpolatedStringHandler.AppendLiteral("http://");
			defaultInterpolatedStringHandler.AppendFormatted(this._serverIp);
			defaultInterpolatedStringHandler.AppendLiteral(":");
			defaultInterpolatedStringHandler.AppendFormatted(this._port);
			defaultInterpolatedStringHandler.AppendLiteral("/CapService/CapSyncReadMulti?pipeNo=0&timeout=3000");
			RestResponse restResponse = HttpUtil.RequestBehaviorSync(defaultInterpolatedStringHandler.ToStringAndClear(), Method.Get, "", isToken: true, isJson: true, keepAlive: true, dictionary);
			if (!restResponse.IsSuccessful)
			{
				gOperateAmdRet.Message = restResponse.ErrorMessage;
				return gOperateAmdRet;
			}
			GOperateAmdRet<Dictionary<string, string>> gOperateAmdRet2 = JsonConvert.DeserializeObject<GOperateAmdRet<Dictionary<string, string>>>(restResponse.Content);
			if (!gOperateAmdRet2.Success)
			{
				gOperateAmdRet.Message = gOperateAmdRet2.Message;
				return gOperateAmdRet;
			}
			if (int.TryParse(gOperateAmdRet2.Content[text3], out result) && int.TryParse(gOperateAmdRet2.Content[text4], out result2))
			{
				gOperateAmdRet.Success = true;
				gOperateAmdRet.Content = new Tuple<int, int>(result, result2);
				return gOperateAmdRet;
			}
			gOperateAmdRet.Message = "convert to int failed";
			return gOperateAmdRet;
		}

		public GOperateAmdRet<Dictionary<string, string>> QueryMasterSrcPlace(List<int> tnoList)
		{
			if (tnoList == null)
			{
				throw new ArgumentNullException("tnoList");
			}
			GOperateAmdRet<Dictionary<string, string>> gOperateAmdRet = new GOperateAmdRet<Dictionary<string, string>>();
			if (tnoList.Count <= 0)
			{
				gOperateAmdRet.Message = "error Tno";
				return gOperateAmdRet;
			}
			List<string> list = new List<string>();
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler;
			foreach (int tno in tnoList)
			{
				defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(27, 1);
				defaultInterpolatedStringHandler.AppendLiteral("/Tool/Data/toolMyPlace[u1,");
				defaultInterpolatedStringHandler.AppendFormatted(tno, "D5");
				defaultInterpolatedStringHandler.AppendLiteral("]");
				list.Add(defaultInterpolatedStringHandler.ToStringAndClear());
			}
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			string value = JsonConvert.SerializeObject(list);
			dictionary.Add("Custom-Param1", value);
			defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(49, 2);
			defaultInterpolatedStringHandler.AppendLiteral("http://");
			defaultInterpolatedStringHandler.AppendFormatted(this._serverIp);
			defaultInterpolatedStringHandler.AppendLiteral(":");
			defaultInterpolatedStringHandler.AppendFormatted(this._port);
			defaultInterpolatedStringHandler.AppendLiteral("/CapService/CapSyncReadMulti?timeout=3000");
			RestResponse restResponse = HttpUtil.RequestBehaviorSync(defaultInterpolatedStringHandler.ToStringAndClear(), Method.Get, "", isToken: true, isJson: true, keepAlive: true, dictionary, this.HttpRequestTimeout);
			if (!restResponse.IsSuccessful)
			{
				gOperateAmdRet.Message = restResponse.ErrorMessage;
				return gOperateAmdRet;
			}
			GOperateAmdRet<Dictionary<string, string>> gOperateAmdRet2 = JsonConvert.DeserializeObject<GOperateAmdRet<Dictionary<string, string>>>(restResponse.Content);
			if (!gOperateAmdRet2.Success)
			{
				gOperateAmdRet.Message = gOperateAmdRet2.Message;
				return gOperateAmdRet;
			}
			gOperateAmdRet.Success = true;
			gOperateAmdRet.Content = gOperateAmdRet2.Content;
			return gOperateAmdRet;
		}

		[Obsolete("use QueryEmptyPlace method instead")]
		public GOperateAmdRet<List<int>> QueryMasterSrcPlace(List<ToolEntitySimple> entities)
		{
			GOperateAmdRet<List<int>> gOperateAmdRet = new GOperateAmdRet<List<int>>();
			List<ToolEntitySimple> list = entities.Where((ToolEntitySimple x) => x.ToolInMag == 9998).ToList();
			if (list.Count == 0)
			{
				gOperateAmdRet.Success = true;
				return gOperateAmdRet;
			}
			List<string> list2 = new List<string>();
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler;
			foreach (ToolEntitySimple item in list)
			{
				defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(27, 1);
				defaultInterpolatedStringHandler.AppendLiteral("/Tool/Data/toolMyPlace[u1,");
				defaultInterpolatedStringHandler.AppendFormatted(item.ToolNo, "D5");
				defaultInterpolatedStringHandler.AppendLiteral("]");
				list2.Add(defaultInterpolatedStringHandler.ToStringAndClear());
			}
			StringBuilder stringBuilder = new StringBuilder();
			string value = JsonConvert.SerializeObject(list2);
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			dictionary.Add("Custom-Param1", value);
			defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(50, 2);
			defaultInterpolatedStringHandler.AppendLiteral("http://");
			defaultInterpolatedStringHandler.AppendFormatted(this._serverIp);
			defaultInterpolatedStringHandler.AppendLiteral(":");
			defaultInterpolatedStringHandler.AppendFormatted(this._port);
			defaultInterpolatedStringHandler.AppendLiteral("/CapService/CapSyncReadSingle?timeout=3000");
			RestResponse restResponse = HttpUtil.RequestBehaviorSync(defaultInterpolatedStringHandler.ToStringAndClear(), Method.Get, "", isToken: true, isJson: true, keepAlive: true, dictionary, this.HttpRequestTimeout);
			if (!restResponse.IsSuccessful)
			{
				gOperateAmdRet.Message = restResponse.ErrorMessage;
				return gOperateAmdRet;
			}
			GOperateAmdRet<Dictionary<string, string>> gOperateAmdRet2 = JsonConvert.DeserializeObject<GOperateAmdRet<Dictionary<string, string>>>(restResponse.Content);
			if (!gOperateAmdRet2.Success)
			{
				gOperateAmdRet.Message = gOperateAmdRet2.Message;
				return gOperateAmdRet;
			}
			gOperateAmdRet.Success = true;
			gOperateAmdRet.Content = gOperateAmdRet2.Content.Values.Select((string x) => int.Parse(x)).ToList();
			return gOperateAmdRet;
		}

		private OperateAmdRet ExcutePi(string command, params string[] argBuf)
		{
			OperateAmdRet operateAmdRet = new OperateAmdRet();
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			List<string> list = new List<string>();
			foreach (string text in argBuf)
			{
				if (!string.IsNullOrWhiteSpace(text))
				{
					list.Add(text);
				}
			}
			dictionary.Add("Custom-Param1", JsonConvert.SerializeObject(list));
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(41, 3);
			defaultInterpolatedStringHandler.AppendLiteral("http://");
			defaultInterpolatedStringHandler.AppendFormatted(this._serverIp);
			defaultInterpolatedStringHandler.AppendLiteral(":");
			defaultInterpolatedStringHandler.AppendFormatted(this._port);
			defaultInterpolatedStringHandler.AppendLiteral("/CapService/CapPiStart?szCommand=");
			defaultInterpolatedStringHandler.AppendFormatted(command);
			RestResponse restResponse = HttpUtil.RequestBehaviorSync(defaultInterpolatedStringHandler.ToStringAndClear(), Method.Get, "", isToken: true, isJson: true, keepAlive: true, dictionary, this.HttpRequestTimeout);
			if (!restResponse.IsSuccessful)
			{
				operateAmdRet.Message = restResponse.ErrorMessage;
				return operateAmdRet;
			}
			return JsonConvert.DeserializeObject<OperateAmdRet>(restResponse.Content);
		}

		public GOperateAmdRet<List<MagConfigEntity>> QueryMagConfig()
		{
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(34, 2);
			defaultInterpolatedStringHandler.AppendLiteral("http://");
			defaultInterpolatedStringHandler.AppendFormatted(this._serverIp);
			defaultInterpolatedStringHandler.AppendLiteral(":");
			defaultInterpolatedStringHandler.AppendFormatted(this._port);
			defaultInterpolatedStringHandler.AppendLiteral("/CapService/QueryMagConfig");
			RestResponse restResponse = HttpUtil.RequestBehaviorSync(defaultInterpolatedStringHandler.ToStringAndClear(), Method.Get, "", isToken: true, isJson: true, keepAlive: true, null, this.HttpRequestTimeout);
			if (!restResponse.IsSuccessful)
			{
				return new GOperateAmdRet<List<MagConfigEntity>>
				{
					Message = restResponse.ErrorMessage
				};
			}
			return JsonConvert.DeserializeObject<GOperateAmdRet<List<MagConfigEntity>>>(restResponse.Content);
		}

		public void StartToolSync(DbAppConfig dbConfig, ref Action<string, List<ToolChangeInfo>> toolChangeNotify, int toolSyncCheckTime = 3000)
		{
			toolChangeNotify = (Action<string, List<ToolChangeInfo>>)Delegate.Remove(toolChangeNotify, new Action<string, List<ToolChangeInfo>>(ToolChange));
			toolChangeNotify = (Action<string, List<ToolChangeInfo>>)Delegate.Combine(toolChangeNotify, new Action<string, List<ToolChangeInfo>>(ToolChange));
			this.StartToolSync(dbConfig, toolSyncCheckTime);
		}

		public void StartToolSync(DbAppConfig dbConfig, int toolSyncCheckTime = 3000)
		{
			if (dbConfig == null)
			{
				throw new ArgumentNullException("dbConfig");
			}
			if (this.DeviceNo == null)
			{
				throw new ArgumentNullException("DeviceNo");
			}
			if (this._deviceCacheDal == null)
			{
				this._deviceCacheDal = new ToolDeviceCacheDal(dbConfig);
			}
			if (this._toolMagConfigDal == null)
			{
				this._toolMagConfigDal = new ToolMagConfigDal(dbConfig);
			}
			while (!this._toolSyncIniCompleted)
			{
				Thread.Sleep(toolSyncCheckTime);
				GOperateRet<List<OpcUaToolBaseEntity>> gOperateRet = this.QueryToolAll();
				if (!gOperateRet.Success)
				{
					continue;
				}
				Thread.Sleep(100);
				GOperateAmdRet<List<MagConfigEntity>> gOperateAmdRet = this.QueryMagConfig();
				if (!gOperateAmdRet.Success)
				{
					continue;
				}
				this.MagConfigTransCommit(gOperateAmdRet.Content);
				this._magCapacityAct = new Dictionary<int, int>();
				foreach (MagConfigEntity item in gOperateAmdRet.Content)
				{
					this._magCapacityAct.Add(item.MagNo, item.MagNrPlaces);
				}
				this._deviceCacheDal.CreateMag(this.FmcNo, this.DeviceNo, this._magCapacityAct, 1);
				this.ToolCacheSyncDev(gOperateRet);
				this._toolSyncIniCompleted = true;
			}
		}
		/// <summary>
		/// 刀库配置提交
		/// </summary>
		/// <param name="list"></param>
		private void MagConfigTransCommit(List<MagConfigEntity> list)
		{
			List<ToolMagConfigEntity> list2 = new List<ToolMagConfigEntity>();
			foreach (MagConfigEntity item in list)
			{
				ToolMagConfigEntity toolMagConfigEntity = DataConverter.DeepCopy<MagConfigEntity, ToolMagConfigEntity>(item);
				toolMagConfigEntity.DeviceNo = this.DeviceNo;
				toolMagConfigEntity.FMCNo = this.FmcNo;
				toolMagConfigEntity.TimeStamp = DateTime.Parse(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
				list2.Add(toolMagConfigEntity);
			}
			this._toolMagConfigDal.TransAdd(this.DeviceNo, list2);
		}
        /// <summary>
        /// 工具缓存同步开发
        /// </summary>
        /// <param name="queryToolAllRet"></param>
        /// <param name="channelNo"></param>
        /// <param name="acceptNotify"></param>
        /// <param name="checkMasterUse"></param>
        /// <returns></returns>

        public OperateResult ToolCacheSyncDev(GOperateRet<List<OpcUaToolBaseEntity>> queryToolAllRet = null, int channelNo = 1, bool acceptNotify = true, bool checkMasterUse = true)
		{
			Thread.Sleep(100);
			OperateResult operateResult = new OperateResult();
			GOperateRet<List<OpcUaToolBaseEntity>> gOperateRet = queryToolAllRet ?? this.QueryToolAll(channelNo, acceptNotify);
			if (!gOperateRet.Success)
			{
				operateResult.Message = operateResult.Message;
				return operateResult;
			}
			List<ToolDeviceCacheUnionEntity> list = this._deviceCacheDal.QueryTools(this.FmcNo, this.DeviceNo);
			if (checkMasterUse)
			{
				ToolMagConfigEntity masterMagConfig = this._toolMagConfigDal.QueryMasterMag(this.DeviceNo);
				if (masterMagConfig != null)
				{
					List<OpcUaToolBaseEntity> content = gOperateRet.Content;
					List<int> list2 = new List<int>();
					List<OpcUaToolBaseEntity> list3 = (from x in content
						where x.ToolInMag == masterMagConfig.MagNo
						where !x.IsEmpty
						select x).ToList();
					if (list3.Count > 0)
					{
						GOperateAmdRet<Dictionary<string, string>> gOperateAmdRet = this.QueryMasterSrcPlace(list3.Select((OpcUaToolBaseEntity x) => x.ToolNo).ToList());
						if (gOperateAmdRet.Success)
						{
							foreach (string key in gOperateAmdRet.Content.Keys)
							{
								list2.Add(int.Parse(gOperateAmdRet.Content[key]));
							}
						}
					}
					foreach (ToolDeviceCacheUnionEntity item in list)
					{
						if (item.ToolInMag == 1 && list2.Contains(item.ToolInPlace))
						{
							item.MasterUse = true;
						}
					}
				}
			}
			Dictionary<ToolDeviceCacheUnionEntity, DbCompareRetEnum> toolCompareRet = this._toolSyncUtil.GetToolCompareRet(list, gOperateRet.Content, ToolInterfaceTypeEnum.QtDev, delegate(ToolDeviceCacheUnionEntity dbEntity, OpcUaToolBaseEntity commEntity)
			{
				if (dbEntity == null)
				{
					dbEntity = new ToolDeviceCacheUnionEntity
					{
						DeviceNo = this.DeviceNo,
						FMCNo = this.FmcNo
					};
					ToolDeviceCacheUnionEntity toolDeviceCacheUnionEntity = ToolSyncUtil.ToolCommToDb(commEntity, dbEntity);
				}
				return dbEntity;
			}, this.CacheToolBuff);
			this._deviceCacheDal.ToolTransCommit(toolCompareRet, ToolInterfaceTypeEnum.QtDev);
			list = this._deviceCacheDal.QueryTools(this.FmcNo, this.DeviceNo);
			this.ToolCacheList = (from x in list
				orderby x.ToolInMag descending, x.ToolInPlace, x.EdgeIndex, x.ToolIdent
				select x).ToList();
			operateResult.IsSuccess = true;
			return operateResult;
		}

		public List<ToolDeviceCacheUnionEntity> GetMagList(int magNo)
		{
			return this.ToolCacheList.Where((ToolDeviceCacheUnionEntity x) => x.ToolInMag == magNo).ToList();
		}

		private void ToolChange(string deviceNo, List<ToolChangeInfo> entities)
		{
			if (!(deviceNo != this.DeviceNo))
			{
				this.ToolCacheSyncDev();
			}
		}
	}
}
